﻿using Blm.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Fms;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Fms;
using VisionCloud.Domain.Repository.Interface.Fms;
using VisionCloud.Domain.UnitOfWork;

namespace VisionCloud.Service.Fms
{
    public class ProjectBuildingFloorService
    {
        public IUnitOfWork UnitOfWork { get; set; }

        public IFmsProjectBuildingFloorRepository BuildingFloorRepository { get; set; }

        public ProjectDCService ProjectDCService { get; set; }

        /// <summary>
        /// 分页获取FMS项目列表（附带楼栋楼层）
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<ApiPageResult> GetList(ProjectBuildlingFloorSearchDto condition)
        {
            var result = await BuildingFloorRepository.GetList(condition);
            return result;
        }

        /// <summary>
        /// 更新FMS项目信息
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> UpdateFmsProject()
        {
            var result = await ProjectDCService.ListWithBuildingFloorsAll();
            if (result == null || result.Data == null || result.Data.Count == 0)
                return new ApiResult { Code = AjaxCode.Fail, Message = "查询FMS项目列表失败" };

            //过滤没有楼栋楼层信息的楼层
            var list = result.Data.Where(p => p.BuildingList != null && p.BuildingList.Count > 0).ToList();
            var newCodeArray = list.Select(p => p.ProjectCode);

            //数据库已存在的项目
            var currProjectList = await BuildingFloorRepository.WhereAsync(p => !p.IsDeleted);
            var currCodeArray = currProjectList.Select(p => p.ProjectCode);
            // 获取已逻辑删除项目
            var currDelProjectList = await BuildingFloorRepository.WhereAsync(p => p.IsDeleted);
            var currDelCodeArray = currProjectList.Select(p => p.ProjectCode);
            if (currProjectList.Count > 0)
            {
                foreach (var project in currProjectList)
                {
                    var item = list.FirstOrDefault(p => p.ProjectCode == project.ProjectCode);
                    if (item == null)
                    {
                        BuildingFloorRepository.Remove(project);
                    }
                    else
                    {
                        project.BuildingList = item.BuildingList.ToJsonStr();
                        BuildingFloorRepository.Update(project);
                    }
                }
            }

            //数据库未存在的项目
            var notExistsProjectList = list.Where(
                p => !currCodeArray.Contains(p.ProjectCode) 
                && !currDelCodeArray.Contains(p.ProjectCode)).ToList();
            int addCnt = 0;
            if (notExistsProjectList.Count > 0)
            {
                List<FmsProjectBuildingFloor> projectList = new List<FmsProjectBuildingFloor>();
                foreach (var item in notExistsProjectList)
                {
                    var project = new FmsProjectBuildingFloor
                    {
                        Id = Guid.NewGuid(),
                        IsDeleted = false,
                        ProjectId = item.ProjectId,
                        ProjectCode = item.ProjectCode,
                        ProjectName = item.ProjectName,
                        BuildingList = item.BuildingList.ToJsonStr(),
                        CreatedDate = DateTime.Now,
                        LastUpdatedDate = DateTime.Now
                    };
                    projectList.Add(project);
                }
                BuildingFloorRepository.AddRange(projectList);
                addCnt = projectList.Count;
            }

            //已被删除的项目
            var deleteProjectList = currProjectList.Where(p => !newCodeArray.Contains(p.ProjectCode)).ToList();
            if (deleteProjectList.Count > 0)
            {
                BuildingFloorRepository.RemoveRange(deleteProjectList);
            }

            await UnitOfWork.SaveChangesAsync();

            return new ApiResult { Code = AjaxCode.Success, Message = $"本次总共新增：{addCnt}笔，删除：{deleteProjectList.Count}笔" };
        }
    }
}
